Skip to main content

Multiple Workers in One File

Piscina allows you to define multiple worker functions within a single file. This approach can be useful when you have related tasks that you want to keep in one module.

In the example below, for each task, pool.run() is called with two arguments:

  • The task data ({ a: 2, b: 3 })
  • An options object specifying the name of the function to use.
index.js
'use strict';

const Piscina = require('piscina');
const { resolve } = require('path');

const pool = new Piscina({ filename: resolve(__dirname, 'worker.js') });

(async () => {
console.log(await Promise.all([
pool.run({ a: 2, b: 3 }, { name: 'add' }),
pool.run({ a: 2, b: 3 }, { name: 'multiply' })
]));
})();
index.mjs
import { Piscina } from 'piscina';

const pool = new Piscina({
filename: new URL('./worker.mjs', import.meta.url).href
});

console.log(await Promise.all([
pool.run({ a: 2, b: 3 }, { name: 'add' }),
pool.run({ a: 2, b: 3 }, { name: 'multiply' })
]));

Here's the worker file that defines multiple functions:

worker.js
'use strict';

function add ({ a, b }) { return a + b; }
function multiply ({ a, b }) { return a * b; };

add.add = add;
add.multiply = multiply;

// The add function is the default handler, but
// additional named handlers are exported.
module.exports = add;
worker.mjs
export function add ({ a, b }) { return a + b; }
export function multiply ({ a, b }) { return a * b; };

You can also check out this example on github.